<?php
namespace yan\xss_sql_filter\validator;
use Yii;
class InjectValidator extends \yii\validators\Validator{
    private $_filter;

    public function init(){
        parent::init();
        if ($this->message === null) {
            $this->message = Yii::t('yii', '{attribute} Error Value');
        }
    }
    public function validateAttribute($model, $attribute){
        $value = $model->$attribute;
        if ($this->validateInject($value) || $this->checkSpecialCharacters($value)) {            
            $this->addError($model, $attribute, $this->message);
        }
    }
    public function validateValue($value){
        if($this->validateInject($value) || $this->checkSpecialCharacters($value)){
            return [$this->message, []];
        }
        return null;
    }
    public function validateInject($values){
        $xssFilter = $this->getFilter();        
        if(is_string($values) && $xssFilter->doCheck($values)){
            return true;
        }else if(!empty($values)){
            foreach((array)$values as $key => $value){
                if($xssFilter->doCheck(json_encode($value))){
                    return true;
                }
            }
        }
        return false;
    }
    private function getFilter(){
        if(empty($this->_filter)){
            $this->_filter = \yan\xss_sql_filter\XssAndSqlFilter::instance();
        }
        return $this->_filter;
    }
    public function checkSpecialCharacters(String $value){
        $pattern = "/[\<|\>|\\|'|\"]/";
        if(preg_match($pattern, $value)){
            return true;
        }
        $value2 = urldecode($value);
        if(preg_match($pattern, $value2)){
            return true;
        }
        $value2 = html_entity_decode($value, ENT_COMPAT, 'UTF-8');
        if(preg_match($pattern, $value2)){
            return true;
        }
        return false;
    }
}